package homework.day03;

import java.io.*;
import java.util.Scanner;

public class Test {
    public static void main(String[] args)  {
        Scanner sc = new Scanner(System.in);
        File file = new File("student.txt");
        ObjectOutputStream oos = null;

        try {
            FileOutputStream fos = new FileOutputStream(file);
             oos = new ObjectOutputStream(fos);

            while(true){
                 System.out.print("请输入学生姓名（输入 q 退出）：");
                 String name = sc.next();
                 if("q".equalsIgnoreCase(name)){
                     break;
                 }
                 System.out.print("请输入学生年龄：");
                 int age = sc.nextInt();

                 System.out.print("请输入学生性别：");
                 String sex = sc.next();

                 Student student = new Student(name,age,sex);
                 oos.writeObject(student);

                 System.out.println("学生信息已写入文件。");

                 printNote();
             }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                oos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }


    }
    public static void printNote()  {
       File file=new File("student.txt");
        ObjectInputStream ois = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ois = new ObjectInputStream(fis);
            Student student ;

            // 循环读取对象，直到文件末尾
            while (true) {
                try {
                    student = (Student) ois.readObject();
                    System.out.println(student);
                } catch (EOFException e) {
                    // 读取到文件末尾，退出循环
                    e.printStackTrace();
                    break;
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            e.getMessage();
        }finally {
            try {
                if(ois != null){
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

//FileInputStream fis = new FileInputStream(file);
//            ois = new ObjectInputStream(fis);
//            Student1 student =null;
//            while((student = (Student1)ois.readObject())!=null){
//                System.out.println(student);
//            }


